#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from django.shortcuts import render, redirect, HttpResponse
from crm import models

enabled_admins = {}


class BaseAdmin(object):
    list_display = []  # 需要展示的字段
    list_filters = []  # 需要筛选的字段
    search_fields = []  # 需要搜索的字段
    list_per_page = 5  # 配置每页展示多少条数据
    filter_horizontal = []  # 配置复选框
    readonly_fields = []  # 配置不可编辑项
    actions = ["delete_selected_objs"]  # 配置操作
    modelform_exclude_fields = []  # 不展示的字段
    readonly_table = False

    def delete_selected_objs(self, request, querysets):
        print(self, request, querysets)
        app_name = self.model._meta.app_label
        table_name = self.model._meta.model_name
        errors = {}
        if self.readonly_table:
            errors = {"readonly_table": " This table is readonly , cannot be delete"}
        if request.POST.get("delete_confirm") == "yes":
            if not self.readonly_table:
                querysets.delete()
                return redirect("/kingadmin/%s/%s/" % (app_name, table_name))
        selected_ids = ','.join([str(i.id) for i in querysets])
        return render(request, "kingadmin/table_obj_delete.html", {"objs": querysets,
                                                                   "admin_class": self,
                                                                   "app_name": app_name,
                                                                   "table_name": table_name,
                                                                   "selected_ids": selected_ids,
                                                                   "action": request._admin_action,
                                                                   "errors": errors})

    delete_selected_objs.display_name = "批量删除"

    def default_from_validation(self):
        '''用户可以在此进行自定义的表单验证，相当于django form的clean方法'''
        pass


class CustomerAdmin(BaseAdmin):
    list_display = ['id', 'qq', 'name', 'source', 'consultant', 'consult_course', 'date', 'status', 'enroll']
    list_filters = ['source', 'consultant', 'consult_course', 'date']
    search_fields = ['qq', 'name', 'consult_course__name']
    filter_horizontal = ['tags']
    readonly_fields = ['qq', 'consultant', 'tags']

    # readonly_table = True

    def default_from_validation(self):
        consult_content = self.cleaned_data.get("content", '')
        if len(consult_content) < 15:
            return self.ValidationError(
                ('Field %(field)s 咨询内容不能少于15个字符'),
                code='invalid',
                params={'field': "content", },
            )

    def clean_name(self):
        print("claen_name", self.cleaned_data["name"])
        if not self.cleaned_data["name"]:
            self.add_error('name', "cannot be null")
        else:
            return self.cleaned_data["name"]

    def enroll(self):
        if self.instance.status == 1:
            link_name = "报名新课程"
        else:
            link_name = "报名"
        return '''<a href="/crm/customer/%s/enrollment/"> %s</a>''' % (self.instance.id, link_name)

    enroll.display_name = "报名链接"


class CustomerFollowUpAdmin(BaseAdmin):
    list_display = ('customer', 'consultant', 'date')


class RoleAdmin(BaseAdmin):
    list_display = ('name', 'menus')


class StudyRecordAdmin(BaseAdmin):
    list_display = ['student', 'course_record', 'attendance', 'score', 'date']
    list_filters = ['course_record', 'score', 'attendance']
    # list_editable = ['attendance']  # 行内可编辑


class CourseRecordAdmin(BaseAdmin):
    list_display = ('from_class', 'day_num', 'teacher', 'has_homework', 'homework_title', 'date')
    actions = ["delete_selected_objs", 'initialize_studyrecords']

    def initialize_studyrecords(self, request, queryset):
        if len(queryset) > 1:
            return HttpResponse("只能选择一个班级")
        print(queryset[0].from_class.enrollment_set.all())
        new_obj_list = []
        for enroll_obj in queryset[0].from_class.enrollment_set.all():
            #     models.StudyRecord.objects.get_or_create(
            #         student=enroll_obj,
            #         course_record=queryset[0],
            #         attendance=0,
            #         score=0,
            #     )

            new_obj_list.append(models.StudyRecord(
                student=enroll_obj,
                course_record=queryset[0],
                attendance=0,
                score=0,
            ))

        try:
            models.StudyRecord.objects.bulk_create(new_obj_list)  # 批量创建
        except Exception as e:
            return HttpResponse("批量初始化学习记录失败，请检查该节课已经有对应的学习记录")
        return redirect("/kingadmin/crm/studyrecord/?course_record=%s" % queryset[0].id)

    initialize_studyrecords.display_name = "初始化本节所有学员的上课记录"


class UserProfileAdmin(BaseAdmin):
    list_display = ('email', 'name')
    readonly_fields = ('password',)
    filter_horizontal = ('user_permissions', 'groups')
    modelform_exclude_fields = ('last_login',)


def register(model_class, admin_class=None):
    if model_class._meta.app_label not in enabled_admins:
        enabled_admins[model_class._meta.app_label] = {}
        # model_class._meta.app_label 获取APP的名字 enabled_admins['crm']={}

    admin_class.model = model_class
    enabled_admins[model_class._meta.app_label][model_class._meta.model_name] = admin_class
    # 相当于 enabled_admins['crm']['Customer']=CustomerAdmin


register(models.Customer, CustomerAdmin)
register(models.CustomerFollowUp, CustomerFollowUpAdmin)
register(models.Role, RoleAdmin)
register(models.UserProfile, UserProfileAdmin)
register(models.StudyRecord, StudyRecordAdmin)
register(models.CourseRecord, CourseRecordAdmin)
